package com.bac.rentmap.web.controller.ad.manage;

import com.bac.rentmap.ad.flat.FlatAd;
import com.bac.rentmap.ad.flat.image.FlatImage;
import com.bac.rentmap.ad.flat.image.FlatImageService;
import com.bac.rentmap.ad.flat.image.FlatImageType;
import com.bac.rentmap.ad.flat.jdo.CachingJdoFlatAdDao;
import com.bac.rentmap.ad.flat.jdo.JdoFlatAdDao;
import com.bac.rentmap.ad.flat.jdo.JdoHelper;
import com.bac.rentmap.web.controller.ad.add.AddFlatController;

import com.google.appengine.api.datastore.Key;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by Andrew Osipenko.
 */
public class FlatAdEditController extends SimpleFormController {
    private static final Logger log = Logger
            .getLogger(FlatAdEditController.class.getName());

    private PersistenceManagerFactory persistenceManagerFactory;
    private JdoFlatAdDao jdoFlatAdDao;
    private CachingJdoFlatAdDao cachingJdoFlatAdDao;
    private FlatImageService flatImageService;
    private JdoHelper jdoHelper;

    protected ModelAndView onSubmit(HttpServletRequest request,
                                    HttpServletResponse response, Object command, BindException errors)
            throws Exception {
        FlatAdBean flatAdBean = (FlatAdBean) command;
        PersistenceManager persistenceManager = getPersistenceManager();
        FlatAd flatAd;
        try {
            flatAd = jdoFlatAdDao.loadBySecureId(flatAdBean.getSecureId(), persistenceManager);
            flatAd.setRatingCalculated(false);
            flatAd.setPrice(flatAdBean.getPrice());
            flatAd.setDescription(flatAdBean.getDescription());
            flatAd.setLastPublishingDate(new Date());
            flatImageService.updateFlatAdImages(flatAd.getSecureId(), flatAd);
        }
        finally {
            persistenceManager.close(); // and save flatAd
        }
        cachingJdoFlatAdDao.removeFromCache(flatAd.getId());

        response.sendRedirect("/ad/manage/view.do?saveSuccessMessage=true&secureId="
                + flatAdBean.getSecureId());
        return null;
    }

    @Override
    protected void onBindOnNewForm(HttpServletRequest request, Object command) throws Exception {
        FlatAdBean flatAdBean = (FlatAdBean) command;
        String secureId = request.getParameter("secureId");
        log.fine("showForm: secureId=" + secureId);
        PersistenceManager persistenceManager = getPersistenceManager();
        FlatAd flatAd;
        try {
            flatAd = jdoFlatAdDao.loadBySecureId(flatAdBean.getSecureId(), persistenceManager);
            flatAdBean.setSecureId(secureId);
            flatAdBean.setPrice(flatAd.getPrice());
            flatAdBean.setDescription(flatAd.getDescription());
            Key flatAdKey = jdoHelper
                    .convertToFlatAdKey(flatAd.getId());
            List<FlatImage> flatImageList = flatImageService.getFlatImages(flatAdKey, persistenceManager);
            Map<String, Long> flatImages = new HashMap<String, Long>();
            flatAdBean.setFlatImages(flatImages);
            for(FlatImage flatImage: flatImageList){
                flatImages.put(flatImage.getType().name(), flatImage.getId());
            }
        }
        finally {
            persistenceManager.close();
        }
    }

    @Override
    protected Map<String, Object> referenceData(HttpServletRequest request)
            throws Exception {
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("imageTypes", AddFlatController.getFlatImageTypeNames());
        return res;
    }

    protected PersistenceManager getPersistenceManager() {
        return persistenceManagerFactory.getPersistenceManager();
    }

    @Required
    public void setPersistenceManagerFactory(PersistenceManagerFactory persistenceManagerFactory) {
        this.persistenceManagerFactory = persistenceManagerFactory;
    }
    @Required
    public void setJdoFlatAdDao(JdoFlatAdDao jdoFlatAdDao) {
        this.jdoFlatAdDao = jdoFlatAdDao;
    }

    public void setJdoHelper(JdoHelper jdoHelper) {
        this.jdoHelper = jdoHelper;
    }

    public void setFlatImageService(FlatImageService flatImageService) {
        this.flatImageService = flatImageService;
    }

    @Required
    public void setCachingJdoFlatAdDao(CachingJdoFlatAdDao cachingJdoFlatAdDao) {
        this.cachingJdoFlatAdDao = cachingJdoFlatAdDao;
    }
}
